package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.constant.RegionInfoConstant;
import com.sto.stoapp.db.manager.BillcodeManager;
import com.sto.stoapp.db.manager.OrderManager;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.ScanTypeEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.BillControlsUtil;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoHhmRadioButton;
import com.sto.stoapp.widget.StoHhmRadioButton.KeyUpListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class SalesNoPhoneRecvContentActivity extends StoListenerActivity implements RegionInfoConstant {
	// private StoHhmEditText code;
	private StoHhmEditText destination;
	// private TextView ticketNumber, displayScanCode;
	// private RadioButton goods, notgoods;
	private StoHhmRadioButton goods, notgoods;
	private List<EditText> edit = new ArrayList<EditText>();
	private int itemType = 1;

	private String busiType = "";

	private String busiValue = "";
	private String pickupNetwork = ""; // 取件网点
	private Boolean orderIsOper = false; // 订单是否操作
	private BillcodeManager mBillcodeMgr;
	private String destinationCode = "";
	private String destinationName = "";
	private BaseDialog mDialog;
	private DataBusinessEntity dataBusiness;
	private final int DESTINATION_RESULT = 0xfd;
	private String titleType = "普通收件";

	private TextView weight;
	private float blueWeight = -1;
	private String billNo="";
	private BaseDialog filterDialog=null;

	private BaseDialog control2Dialog ,control3Dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_no_phone_recv_content);
		this.setTitleBottom(R.string.no_phone_recv,
				HomeBroadAction.SALES_MAN_BROAD);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		Bundle extras = getIntent().getExtras();
		initBusiType(extras.getString("busiType"));
		titleType = extras.getString("titleType");
		if(titleType ==null ){
			titleType = "普通收件";
		}
		IS_SECURITY_SCAN = checkSiteZJ();

		bluetoothConnect();

	}

	private void initWidget() {
		goods = (StoHhmRadioButton) this
				.findViewById(R.id.nophone_goods_sample);
		notgoods = (StoHhmRadioButton) this
				.findViewById(R.id.nophone_no_goods_sample);
		destination = (StoHhmEditText) this
				.findViewById(R.id.nophone_destination_text);
		code = (StoHhmEditText) this
				.findViewById(R.id.nophone_odd_numbers_text);
		weight = (TextView) this.findViewById(R.id.enter_count);
		// ticketNumber = (TextView)
		// this.findViewById(R.id.nophone_tickets_text);
		edit.add(destination);
		// edit.add(code);
		mBillcodeMgr = BillcodeManager.getInstance(this);
		mDialog = new BaseDialog(this);
		mDialog.openScanKeyListener(true);
		mDialog.setEnabledKeyEvent(false);
		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT)) {
			addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT);
		}
		addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE);
	}

	private void initBusiType(String busiData) {
		String[] data = busiData.split("\\|");
		busiType = data[0];
		busiValue = data[1];
		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT)) {
			pickupNetwork = data[2];
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT);
		} else {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE);
		}
	}

	/**
	 * 监听控件
	 */
	private void initListen() {

		findViewById(R.id.home).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// System.out.println("***setTitleBottom***");
				homePressed();
			}
		});

		findViewById(R.id.back).setOnClickListener(
				new StoOnClickListener(this) {

					@Override
					public void mHonClick(View view) {
						// Helper.showToast(SalesPhoneRecvContentActivity.this,
						// "test");
						onBackPressed();
					}
				});

		mDialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				if (res)
					mDialog.dismiss();
			}
		});
		goods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 1;
				notgoods.setChecked(false);
			}
		});

		notgoods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 2;
				goods.setChecked(false);
			}
		});

		goods.setKeyUpBack(new KeyUpListener() {

			@Override
			public void onKeyUpBack() {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});

		notgoods.setKeyUpBack(new KeyUpListener() {

			@Override
			public void onKeyUpBack() {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});

		destination.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				goods.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
//				selectDestination();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectDestination();
			}
		});

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				destination.requestFocus();
				// destination.setSelection(destination.getText().toString().length());
				// destination.selectAll();
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
			}
		});

		for (EditText editListener : edit) {

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					if (destination.getText().toString().equals("")) {
						destinationCode = "";
						destinationName = "";
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
	}

	/**
	 * 选择目的地
	 */
	private void selectDestination() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (destination.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_REGION_INFO_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_REGION_INFO_ONLY_LIKE);
				tableParcel.setSelectField(new String[] {
						"%"+destination.getText().toString() + "%",
						"%"+destination.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(CODE);
			tableParcel.setSelectName(NAME);
			tableParcel.setProperty(null);

			Intent intent = new Intent(SalesNoPhoneRecvContentActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, DESTINATION_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectDestination", e.getMessage());
		}
	}

	/**
	 * 单号逻辑处理判断
	 * 
	 * @author wxf
	 * 
	 */
	private void codeProcess() {
		String codeName = code.getText().toString();

		GetTableParcel data;
		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			if (codeName.length() <= DESTINATION_LENGTH) {
				data = queryDestination(codeName);
				if (data != null) {
					destination.setText(data.getSelectName());
					destinationCode = data.getSelectCode();
					destinationName = data.getSelectName();

				} else {
					destinationName = "";
					Helper.showSoundToast(this, getString(R.string.undefined),
							false);
				}
				code.setText("");
			} else {
				onScanResults(codeName);
			}
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this).ScanCodeResolve(
				code, EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE);
		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT)) {

			status = ProcessScanCode.getInstance(this).ScanCodeResolve(code,
					EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT);
		}

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(
			// SalesNoPhoneRecvContentActivity.this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(SalesNoPhoneRecvContentActivity.this,
					getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 验证面单发放 cjb
	 * 
	 * @param codeStr
	 */
	private void verifyCode(String codeStr) {
		if (!mBillcodeMgr.queryCodeBySize(codeStr)) {
			mDialog.setTitles("此单号【" + codeStr + "】半年内无发放记录，请核查是否为本网点面单");
			mDialog.show();
			mDialog.getvCanncel().setVisibility(View.GONE);
		}
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (!weight.getText().toString().isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				return;
			}

			if (!code.getText().toString().isEmpty()
					&& destinationName.equals(destination.getText().toString())) {

				billNo=code.getText().toString();

				float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();
				if(blueWeight>maxWeight){
					ScanOff();
					filterDialog=new BaseDialog(this);
					filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
					filterDialog.show();
					Helper.playSound(SalesNoPhoneRecvContentActivity.this);//提示音
					filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							//Add by wj过滤单号
							boolean isFilter= BillFilterUtil.isFilter(billNo,SalesNoPhoneRecvContentActivity.this);
							if(isFilter){
								showFilterDialog(billNo);
								return;
							}
							//End by wj

							int onOff=StoFilePreference.getInstance(SalesNoPhoneRecvContentActivity.this).
									getControlsOnOff();
							if(2==onOff){
								//允许用户点击添加
								boolean isControls=BillControlsUtil.isControls(SalesNoPhoneRecvContentActivity.this,billNo);
								if(isControls){
									ScanOff();
									control2Dialog=new BaseDialog(SalesNoPhoneRecvContentActivity.this);
									control2Dialog.setTitles("此单号【" + billNo + "】非本网点面单或此单号已过期");
									control2Dialog.show();
									Helper.playSound(SalesNoPhoneRecvContentActivity.this);//提示音
									control2Dialog.getvCanncel().setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											control2Dialog.dismiss();
											return;
										}
									});
									control2Dialog.getvAccept().setOnClickListener(new View.OnClickListener() {
										@Override
										public void onClick(View v) {
											control2Dialog.dismiss();
											//End by wj
											addItem(billNo);
										}
									});
								}else {
									addItem(billNo);
								}

							}else if(3==onOff){

								boolean isControls=BillControlsUtil.isControls(SalesNoPhoneRecvContentActivity.this,billNo);
								if(isControls){
									ScanOff();
									//不允许添加
									control3Dialog=new BaseDialog(SalesNoPhoneRecvContentActivity.this);
									control3Dialog.setTitles("此单号【" + billNo + "】非本网点面单或此单号已过期！");
									control3Dialog.show();
									Helper.playSound(SalesNoPhoneRecvContentActivity.this);//提示音
									control3Dialog.setCancelable(false);
									control3Dialog.getvCanncel().setVisibility(View.GONE);
									control3Dialog.getvAccept().setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											control3Dialog.dismiss();
											return;
										}
									});
									return;//不允许后续操作
								}else {
									addItem(billNo);
								}
							}else {
								addItem(billNo);
							}

						}
					});
				}else {
					//Add by wj过滤单号
					boolean isFilter= BillFilterUtil.isFilter(billNo,this);
					if(isFilter){
						showFilterDialog(billNo);
						return;
					}
					//End by wj

					//Add by wj订单管控
					int onOff=StoFilePreference.getInstance(SalesNoPhoneRecvContentActivity.this).
							getControlsOnOff();
					if(2==onOff){
						//允许用户点击添加
						boolean isControls=BillControlsUtil.isControls(SalesNoPhoneRecvContentActivity.this,billNo);
						if(isControls){
							control2Dialog=new BaseDialog(SalesNoPhoneRecvContentActivity.this);
							control2Dialog.setTitles("此单号【" + billNo + "】非本网点面单或此单号已过期！");
							control2Dialog.show();
							Helper.playSound(SalesNoPhoneRecvContentActivity.this);//提示音
							control2Dialog.getvCanncel().setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									control2Dialog.dismiss();
									return;
								}
							});
							control2Dialog.getvAccept().setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									control2Dialog.dismiss();
									addItem(billNo);
								}
							});
						}else {
							addItem(billNo);
						}
					}else if(3==onOff){
						boolean isControls=BillControlsUtil.isControls(SalesNoPhoneRecvContentActivity.this,billNo);
						if(isControls){
							ScanOff();
							//不允许添加
							control3Dialog=new BaseDialog(SalesNoPhoneRecvContentActivity.this);
							control3Dialog.setTitles("此单号【" + billNo + "】非本网点面单或此单号已过期！");
							control3Dialog.show();
							Helper.playSound(SalesNoPhoneRecvContentActivity.this);//提示音
							control3Dialog.setCancelable(false);
							control3Dialog.getvCanncel().setVisibility(View.GONE);
							control3Dialog.getvAccept().setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									control3Dialog.dismiss();
									return;
								}
							});
							return;//不允许后续操作
						}else {
							addItem(billNo);
						}
					}else {
						addItem(billNo);
					}
				}

			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			} else if (!destinationName
					.equals(destination.getText().toString())) {
				// 提示目的地
				Helper.showSoundToast(this, "请选择正确的目的地!", false);
				destination.requestFocus();
				destination.setText("");
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	@Override
	protected void onResume() {
		CONTINUATION_SCAN = true;
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		bluetoothHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);
		super.onDestroy();
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord(String billNo) {
		boolean ret;
		System.out.println("busiType:" + busiType);
		dataBusiness.setBar_code_number(billNo);
		
		dataBusiness.setCodeType(getExpType(billNo));
		// 物品类别
		dataBusiness.setFunction_type(String.valueOf(itemType));

		// 目的地
		dataBusiness.setNext_station(destinationCode);

		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}

		if (destinationCode.equals("")) {
			dataBusiness.setUser_defined3("");
		} else {
			dataBusiness.setUser_defined3(destination.getText().toString());
		}
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());

		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());

		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT)) {
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT.getOpCode());
			// 订单编号
			dataBusiness.setReason_number(busiValue);
			// 取件网点
			dataBusiness.setUser_defined4(pickupNetwork);

			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT);

			// 删除订单编号
			// deleteOrder(busiValue);
			if (ret) {
				this.addCodeNumber();
			}
		}else{
			dataBusiness.setExpress_type(busiValue);
		}
		// 取件网点
		dataBusiness.setUser_defined4("");
		dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE.getOpCode());
		
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE);

		return ret;
	}

	/**
	 * 删除订单
	 * 
	 * @param OrderCode
	 */
	private void deleteOrder(String OrderCode) {
		OrderManager.getInstance(this).deleteOnly(busiValue);
	}

	/**
	 * 更新订单操作状态
	 * 
	 * @param OrderCode
	 */
	private void updateOrderStatu(String OrderCode) {
		OrderManager.getInstance(this).updateOrder(busiValue, "1");
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == DESTINATION_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			destination.setText(courierEntity.getSelectName());
			destination.setSelection(destination.length());
			destinationCode = courierEntity.getSelectCode();

			if (destinationCode.length() > 0)
				destinationName = courierEntity.getSelectName();
			code.requestFocus();
		} else if (requestCode == DESTINATION_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			destination.setText("");
			destinationCode = "";
			destinationName = "";
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		} else {

		}
	}

	/**
	 * home键返回提示
	 */
	private void homePressed() {
		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT) && orderIsOper) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.order_is_finish));
			dialog.show();
			dialog.setOnBackClickListener(new OnBackClickListener() {
				@Override
				public void onBackClickListener(boolean res) {
					// Intent intent = new Intent();
					if (res) {
						// 删除订单编号
						deleteOrder(busiValue);
						// intent.putExtra("ValueName", "true");
						// setResult(RESULT_OK, intent);
					} else {
						// intent.putExtra("ValueName", "OrderOper");
						// setResult(RESULT_FIRST_USER, intent);
					}
					dialog.dismiss();
					Intent intent = new Intent(HomeBroadAction.SALES_MAN_BROAD);
					sendBroadcast(intent);
				}
			});
		} else {
			Intent intent = new Intent(HomeBroadAction.SALES_MAN_BROAD);
			sendBroadcast(intent);
		}

	}

	@Override
	public void onBackPressed() {
		if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT) && orderIsOper) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.order_is_finish));
			dialog.show();
			dialog.setOnBackClickListener(new OnBackClickListener() {
				@Override
				public void onBackClickListener(boolean res) {
					Intent intent = new Intent();
					if (res) {
						// 删除订单编号
						deleteOrder(busiValue);

						// intent.putExtra("ValueName", "true");
						setResult(RESULT_OK, intent);
					} else {
						// intent.putExtra("ValueName", "OrderOper");
						updateOrderStatu(busiValue);
						setResult(RESULT_FIRST_USER, intent);
					}
					dialog.dismiss();
					finishEx();
				}
			});
		} else {
			// 确定退出吗?

			showNotice();

			// super.onBackPressed();
		}
	}

	// 结束当前的activity
	private void finishEx() {
		SalesNoPhoneRecvContentActivity.this.finish();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if(null!=control2Dialog && control2Dialog.isShowing()){
			return;
		}

		if(null!=control3Dialog && control3Dialog.isShowing()){
			return;
		}

		if(CONTINUATION_SCAN) {
			if (scanData != null && !scanData.toString().equals("")) {
				mDialog.dismiss();
				String result = scanData;
				if (result.length() <= DESTINATION_LENGTH) {
					destination.setText(result);
					selectDestination();
				} else {
					code.setText(result);
					code.setSelection(code.length());

					if (CheckScanCode(result)) {
						processScanData();
					}
					code.setText("");
				}
			} else {
				// Helper.showSoundToast(SalesNoPhoneRecvContentActivity.this,
				// "条码不能为空", false);
			}
		}
	}

	/**
	 * 蓝牙连接
	 *
	 * @author wxf
	 *
	 */
	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				// weight.setText(R.string.blue_no_open);
			}
		} else {
			// promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	/**
	 * 蓝牙正式连接
	 */
	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
			// weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this, bluetoothHandler,
					macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	/**
	 * 添加数据
	 */
	private void addItem(String no){
		if (addPieceRecord(no)) {
			addCodeNumber();
			setSaveData(true);
			/**
			 * 判断是否验证面单发放记录
			 *
			 */
			if (StoFilePreference.getInstance(SalesNoPhoneRecvContentActivity.this).getReceiveControl()
					&& !(no.startsWith("33"))) {
				verifyCode(no);
			}

			// SoundManager.getInstance(this).playSuccessSound();
			Helper.showSoundAndVibrator(SalesNoPhoneRecvContentActivity.this, true);
			addScanRecordInfo(no,weight.getText().toString());
			// ticketNumber.setText(String.valueOf(++count));
			code.setSelection(code.length());
			if (busiType.equals(ScanTypeEntity.TYPE_SALES_EXTRACT)) {
				orderIsOper = true;
			}
			if(!orderIsOper){
				if(!titleType.equals("普通收件")) {
					securityProcess(no);
				}
			}
		}
		// 提示插入数据失败
		else {
			Helper.showSoundToast(SalesNoPhoneRecvContentActivity.this,
					getString(R.string.code_repeat), false);
		}
		ScanOpen();
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if (blueConnCount < 3) {
								blueConnecting();
								blueConnCount++;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",正在重连" + blueConnCount + "...");
							} else {
								blueConnCount = 0;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(getText(
									R.string.no_select_scales_model).toString()
									+ "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};
}
